/* 
 */
tdl.require("tdl.buffers");
tdl.require("tdl.fast");
tdl.require("tdl.framebuffers");
tdl.require("tdl.log");
tdl.require("tdl.math");
tdl.require("tdl.quaternions");
tdl.require("tdl.particles");
tdl.require("tdl.primitives");
tdl.require("tdl.programs");
tdl.require("tdl.textures");
tdl.require("tdl.webgl");
tdl.require("tdl.io");

$(document).ready(function(){
	ocean();

	function render(){
		qtre.sceneManager.flush();
		tdl.webgl.requestAnimationFrame(render, qtre.core.canvas);
	}
	render();

	initUI();

	Cufon.replace("h1", {
		textShadow: '0px 1px #ddd',
		fontSize : "26px"
	});
})

var oceanParams = {
		WaveAmp : 0.3,
		WaveFreq : 0.2,
		BumpSpeedX : 0.01,
		BumpSpeedY : 0.01,
		TexReptX : 4,
		TexReptY : 4,
		BumpScale : 1.4,
		FresnelBias : 0.1,
		FresnelExp : 4,
		Kr : 1.0
	}

function ocean(){
	var canvas = document.getElementById("ocean");
	
	gl = qtre.core.initialize(canvas);
	
	//uniform properties
	var eye = new Float32Array([0, 3, 10]);
	var target = new Float32Array([0, 0, 0]);
	var up = new Float32Array([0, 1, 0]);
	
	var skyBoxURL = ['assets/lobby/Sunny1_right.jpg',
						  'assets/lobby/Sunny1_left.jpg',
						  'assets/lobby/Sunny1_up.jpg',
						  'assets/lobby/Sunny1_down.jpg',
						  'assets/lobby/Sunny1_front.jpg',
						  'assets/lobby/Sunny1_back.jpg'];
	/**********************************************************
	 * pass1 : main scene
	 *********************************************************/
	var camera = qtre.sceneManager.createCamera("main", {
		eye : eye,
		target : target,
		up : up,
		fov : tdl.math.degToRad(45),
		near : 1,
		far : 5000
	})

	var fbo = tdl.framebuffers.createFramebuffer(1024, 1024, true);
	fbo.unbind();
	camera.addRenderBeginCallback(function(){
		//todo: fix it up!!
//		this.owner.rotateZ(0.1);
		fbo.bind();
	})
	camera.addRenderEndCallback(function(){
		fbo.unbind();
	})

	var cameraSceneNode = qtre.sceneManager.createSceneNode("camera");
	cameraSceneNode.attachObject(camera);

	camera.setSkyBox(skyBoxURL);
	
	var waveNormalTexture = tdl.textures.loadTexture("assets/waves2.png");
	var reflectionMap = tdl.textures.loadTexture(skyBoxURL);
	
	var program = tdl.programs.loadProgramFromScriptTags(
			'oceanVertexShader',
			'oceanFragmentShader'
		)
	var arrays = tdl.primitives.createPlane(200, 200, 200, 200);
	var ocean = qtre.sceneManager.createRenderable("ocean", arrays);
	var material = qtre.sceneManager.createMaterial("ocean", program);
	material.bindCamera(camera);
	ocean.bindMaterial(material);
	var cameraSceneNode = qtre.sceneManager.createSceneNode("camera");
	cameraSceneNode.attachObject(camera);
	var oceanSceneNode = qtre.sceneManager.createSceneNode("ocean");
	oceanSceneNode.attachObject(ocean);

	material.updateUniforms(oceanParams);
	material.updateUniforms({
		//textures
		normalSampler : waveNormalTexture,
		skyBox : reflectionMap,
		DeepColor : new Float32Array([0, 0, 0.1]),
		ShallowColor : new Float32Array([0, 0.5, 0.5])
	})
	
	ocean.addRenderBeginCallback(function(material){
		material.updateUniforms({
			lightColor : new Float32Array([1, 1, 1, 1]),
			Timer : qtre.sceneManager.time,
		})
	})
	
//	createArticles();
	/********************************************************
	 *depth pass
	 ********************************************************/
	/*
	var depthFBO = tdl.framebuffers.createFramebuffer(512, 512, true);
	
	var depthCamera = qtre.sceneManager.createCamera("depth", {
		eye : eye,
		target : target,
		up : up,
		fov : 45,
		near : 1,
		far : 5000
	})
	depthCamera.addRenderBeginCallback(function(){
		depthFBO.bind();
	})
	depthCamera.addRenderEndCallback(function(){
		depthFBO.unbind();
	})
	cameraSceneNode.attachObject(depthCamera);
	var program = tdl.programs.loadProgramFromScriptTags("depthVertexShader", "depthFragmentShader");
	var material = new qtre.material("depth", program);
	material.bindCamera(depthCamera);
	var renderables =qtre.sceneManager.getRenderables();
	for(var name in renderables){
		renderables[name].bindMaterial(material);
	}
	*/
	/********************************************************
	 * pass2 : post processing - dull polish
	 ******************************************************/
	var program = tdl.programs.loadProgramFromScriptTags('postProcessVertexShader',
													'polishFragmentShader');
	var dullPolishPP = qtre.postProcessing.createPostProcessing(program);
	dullPolishPP.material.updateUniforms({
		diffuse : fbo.texture,
		blurFactor : 10
	})
}

function createArticles(){
	var program = tdl.programs.loadProgramFromScriptTags("articleVertexShader", "articleFragmentShader");
	var material = new qtre.material("article", program);
	material.bindCamera(qtre.sceneManager.getCamera("main"));
	var num = 20;
	for(var i = 0; i < num; i++){
		var arrays = tdl.primitives.createPlane(1, 2, 1, 1);
		var renderable = qtre.sceneManager.createRenderable("article_" + i, arrays);
		var sceneNode = qtre.sceneManager.createSceneNode("article_" + i);
		sceneNode.attachObject(renderable);
		
		renderable.bindMaterial(material);
		renderable.addRenderBeginCallback(function(material){
			material.updateUniforms({
				diffuse: tdl.textures.loadTexture("http://www.qsc.zju.edu.cn/apps/bubble/file.php?file=/data/Files/bubble/thumbfile/30/7d/307d92b1cd52dab5149f2be4346b8086.jpg")
			})
		})
//		sceneNode.translate([(i-num/2)*2, 2, -Math.random() * 20 + 2]);
		sceneNode.translate([(i-num/2)*2, 2, 0]);
		sceneNode.rotateX(Math.PI / 2);
	}
}

function initUI()
{
	initPlayer();
	getCategorys();

	for(var param in oceanParams){
		var value = oceanParams[param];
		var slider = new qtre.ui.slider({
			"min" : 0,
			"max" : value*4,
			"step" : value/20,
			"value" : value
		})
		slider.bindParam(qtre.sceneManager.getMaterial("ocean"), param);
		$("#adjustPanel").append("<h4>"+param+":</h4>")
		$("#adjustPanel").append(slider.instance);
	}
	$("#adjustPanel").append("<br />")
}

function initPlayer()
{
	var player = $("#track");
	player.css("left", $(document.body).width())
	player.css("top", $(document.body).height() - 100);
	player.animate({
		"left" : "-=300"
	}, 1000)

	nextMusic();
	$("#track audio").bind("ended", function(){
		nextMusic();
	})
}

function getCategorys()
{
	$.post("category-ajax.php", {}, function(categories){
		$("#categories").html(categories);
		$("#categories a").click(function(){
			$("iframe").attr("src", $(this).attr("href"));
			return false;
		})
	})
}

function nextMusic(){
	$.post("proxy.php?url=http://www.qsc.zju.edu.cn/apps/bubble/api/?action=get_music", {"user_id": 2955}, function(json){
		var jsonObj = eval("(" + json + ")");
		var music = jsonObj[0];
		music_id = music["music_id"];
		var audio = $("#track audio");
//		audio.attr("src", music["url"]);
		$("#track .title").html(music["title"]);
		musicNow = music;
	})
}